package com.ruoyi.edu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.edu.config.WxMaConfiguration;
import com.ruoyi.edu.domain.EduUser;
import com.ruoyi.edu.service.IEduUserService;
import com.ruoyi.framework.web.domain.WxUser;
import com.ruoyi.framework.web.service.WxLoginService;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import me.chanjar.weixin.common.error.WxErrorException;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@RequestMapping("/wx/user")
public class WxMaUserController {

    @Autowired
    private WxLoginService wxLoginService;

    @Autowired
    private IEduUserService eduUserService;

    /**
     * 微信登录
     * @param appId
     * @param code
     * @param token
     * @return
     */
    @GetMapping("/login")
    public AjaxResult login(String appId, String code, String token) {
        //判断token是否为空
        WxUser wxUser = null;
        if(StringUtils.isNotEmpty(token)){
            wxUser = wxLoginService.getWxUser(token);
        }
        if(StringUtils.isEmpty(token) || StringUtils.isNull(wxUser)){
            if (StringUtils.isBlank(code)) {
                return AjaxResult.error("code不能为空");
            }
            final WxMaService wxService = WxMaConfiguration.getMaService(appId);
            try {
                WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
                wxUser = new WxUser();
                wxUser.setOpenid(session.getOpenid());
                QueryWrapper<EduUser> wrapper = new QueryWrapper<>();
                wrapper.eq("openid", session.getOpenid());
                EduUser eduUser = eduUserService.getOne(wrapper);
                if(StringUtils.isNotNull(eduUser)){
                    if(StringUtils.isNotEmpty(eduUser.getNickname())){
                        //如果昵称不为空，表示之前授权过
                        wxUser.setNickname(eduUser.getNickname());
                        String newtoken = wxLoginService.createToken(wxUser);
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("token", newtoken);
                        eduUser.setNull();
                        map.put("user", eduUser);
                        return AjaxResult.success("登录成功", map);
                    }else {
                        //如果昵称为空，表示非首次登录但是，未授权
                        String newtoken = wxLoginService.createToken(wxUser);
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("token", newtoken);
                        map.put("user", null);
                        return AjaxResult.error("非首次，未授权", map);
                    }
                }else {
                    //首次登录，要把用户信息存入数据库
                    String newtoken = wxLoginService.createToken(wxUser);
                    EduUser user = new EduUser();
                    user.setOpenid(session.getOpenid());
                    eduUserService.save(user);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("token", newtoken);
                    map.put("user", null);
                    return AjaxResult.error("未登录，请授权", map);
                }
            } catch (WxErrorException e) {
                return AjaxResult.error(e.toString());
            }
        }else {
            //token wxUser都不为空
            String nickname = wxUser.getNickname();
            if(StringUtils.isNotEmpty(nickname)){
                //nickname存在，从数据库查找user信息
                QueryWrapper<EduUser> wrapper = new QueryWrapper<>();
                wrapper.eq("openid", wxUser.getOpenid());
                EduUser eduUser = eduUserService.getOne(wrapper);
                //更新缓存
                wxLoginService.setWxUser(wxUser);
                HashMap<String, Object> map = new HashMap<>();
                map.put("token", token);
                eduUser.setNull();
                map.put("user", eduUser);
                return AjaxResult.success("登录成功", map);
            }else {
                //更新缓存
                wxLoginService.setWxUser(wxUser);
                HashMap<String, Object> map = new HashMap<>();
                map.put("token", token);
                map.put("user", null);
                return AjaxResult.error("非首次，未授权", map);
            }
        }
    }

    /**
     * 存储用户信息
     * @param eduUser
     * @param request
     * @return
     */
    @PostMapping("postAuth")
    public AjaxResult postAuth(@RequestBody EduUser eduUser, HttpServletRequest request){
        //根据request获取token
        String token = wxLoginService.getToken(request);
        //根据token获取wxUser
        WxUser wxUser = wxLoginService.getWxUser(token);
        //把nickname存入缓存
        wxUser.setNickname(eduUser.getNickname());
        wxLoginService.setWxUser(wxUser);
        eduUser.setOpenid(wxUser.getOpenid());
        QueryWrapper<EduUser> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", wxUser.getOpenid());
        //更新数据库
        eduUserService.update(eduUser, wrapper);
        return AjaxResult.success("授权成功");
    }


    /**
     *
     * 获取用户信息接口
     *
     */
//    @GetMapping("/info")
//    public String info(@PathVariable String appid, String sessionKey,
//                       String signature, String rawData, String encryptedData, String iv) {
//        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
//
//        // 用户信息校验
//        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
//            return "user check failed";
//        }
//
//        // 解密用户信息
//        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
//
//        return JsonUtils.toJson(userInfo);
//    }
//
//    /**
//     * <pre>
//     * 获取用户绑定手机号信息
//     * </pre>
//     */
//    @GetMapping("/phone")
//    public String phone(@PathVariable String appid, String sessionKey, String signature,
//                        String rawData, String encryptedData, String iv) {
//        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
//
//        // 用户信息校验
//        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
//            return "user check failed";
//        }
//
//        // 解密
//        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
//
//        return JsonUtils.toJson(phoneNoInfo);
//    }

}
